import React, { useReducer, useState } from 'react'
import { jsonClone } from '../../../util';

function initFun () {
  return {
    num1: 1000,
    num2: 1000
  }
}

function myReducer (state, { type, payLoad }) {
  let data = jsonClone(state)
  switch (type) {
    case 'add':
      data.num1 += payLoad
      break;
    case 'sub':
      data.num2 -= payLoad
      break
  }
  return data
}

export default function index() {
  let [val, setVal] = useState(0)

  let [state, dispatch] = useReducer(myReducer, { num1: 100, num2: 100 }, initFun)   //页面上初始值为1000， 执行的initFun

  const inputChange = ($event) => {
    setVal($event.target.value)
  }

  const add = () => {
    dispatch({ type: 'add', payLoad: val })
  }

  const sub = () => {
    dispatch({ type: 'sub', payLoad: val })
  }

  return (
    <div><input type="text" value={val} onInput={inputChange} />
    num1: { state.num1 }
    num2: { state.num2 }
    <button onClick={add}>num1</button>
    <button onClick={sub}>num2</button>
    </div>
  )
}
